<template>
  <Splitpanes class="default-theme">
    <Pane size="50" min-size="20" max-size="80">
      <div class="auth-type">
        <el-radio-group v-model="state.authType" @change="handleChangeAuthType">
          <el-radio :label="AUTH_TYPE_ROLE" size="large">角色授权</el-radio>
          <el-radio :label="AUTH_TYPE_DEPT" size="large">部门授权</el-radio>
          <el-radio :label="AUTH_TYPE_POSITION" size="large">职位授权</el-radio>
        </el-radio-group>
      </div>
      <RoleGrid v-show="state.authType == AUTH_TYPE_ROLE" @select="handleSelectRole" />
      <div v-show="state.authType == AUTH_TYPE_DEPT" style="padding-top: 10px">
        <DeptTree @click="handleSelectDept" />
      </div>
      <PositionGrid v-show="state.authType == AUTH_TYPE_POSITION" @select="handleSelectPosition" />
    </Pane>
    <Pane size="50">
      <div class="role-title">
        <span v-show="state.authType == AUTH_TYPE_ROLE">
          <span v-if="state.currentRole.roleId">{{ state.currentRole.roleName }}</span>
          <span v-else class="empty">请选择授权的角色</span>
        </span>
        <span v-show="state.authType == AUTH_TYPE_DEPT">
          <span v-if="state.currentDept.deptId">{{ state.currentDept.deptName }}</span>
          <span v-else class="empty">请选择授权的部门</span>
        </span>
        <span v-show="state.authType == AUTH_TYPE_POSITION">
          <span v-if="state.currentPosition.positionId">{{ state.currentPosition.positionName }}</span>
          <span v-else class="empty">请选择授权的职位</span>
        </span>
      </div>
      <el-scrollbar :height="menuTreeHeight" style="background-color: #fff">
        <MenuTree
          ref="refMenuTree"
          :disabled="state.disabled"
          :level="1"
          :tree-data="state.treeData"
          :auth-data="state.authData"
          @auth="handleAuth"
        ></MenuTree>
      </el-scrollbar>
    </Pane>
  </Splitpanes>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElScrollbar, ElRadioGroup, ElRadio, ElMessage } from 'element-plus'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import RoleGrid from './RoleGrid.vue'
import PositionGrid from './PositionGrid.vue'
import DeptTree from '@/views/system/dept/DeptTree.vue'
import MenuTree from './MenuTree.vue'
import { menuApi } from '@/api/modules/system/menu'
import { roleApi } from '@/api/modules/system/role'
import { deptApi } from '@/api/modules/system/dept'
import { positionApi } from '@/api/modules/system/position'
import { util } from '@/utils'
import type { Role } from '@/api/modules/system/role'
import type { Dept } from '@/api/modules/system/dept'
import type { Position } from '@/api/modules/system/position'
import type { TreeMenu } from './type'

const AUTH_TYPE_ROLE = 'role'
const AUTH_TYPE_DEPT = 'dept'
const AUTH_TYPE_POSITION = 'position'

// 79 = content.paddingTop + roleTile.height + content.paddingBottom + 5底边高度
const menuTreeHeight = computed(() => util.getContentHeight() - 79)

const state = reactive({
  disabled: true,
  authType: AUTH_TYPE_ROLE,
  treeData: [] as TreeMenu[],
  authData: { menuIds: [] as string[], funcKeys: [] as string[] },
  currentRole: {} as Role,
  currentDept: {} as Dept,
  currentPosition: {} as Position
})

watch(
  [() => state.currentRole, () => state.currentDept, () => state.currentPosition],
  ([newRole, newDept, newPosition]) => {
    console.log(newRole, newDept, newPosition)
    if (newRole.roleId || newDept.deptId || newPosition.positionId) {
      state.disabled = false
    }
  },
  { deep: true }
)

onMounted(() => {
  loadAllMenu()
})
const loadAllMenu = () => {
  menuApi.findAuthMenus().then(resp => {
    if (resp.success) {
      state.treeData = resp.data
    }
  })
}

const handleChangeAuthType = (val: any) => {
  refMenuTree.value.updateStatus([], [])
  if (val == AUTH_TYPE_ROLE && state.currentRole.roleId) {
    getRoleAuth()
  }
  if (val == AUTH_TYPE_DEPT && state.currentDept.deptId) {
    getDeptAuth()
  }
  if (val == AUTH_TYPE_DEPT && state.currentPosition.positionId) {
    getDeptAuth()
  }
}

const refMenuTree = ref()

const handleSelectRole = (role: Role) => {
  state.currentRole = role
  getRoleAuth()
}

const getRoleAuth = () => {
  state.authData = { menuIds: [], funcKeys: [] }
  roleApi.findMenus(state.currentRole.roleId).then(resp => {
    if (resp.success) {
      //都是末级菜单和权限
      state.authData = resp.data

      //递归将菜单及权限的checked更新, indeterminate
      refMenuTree.value.updateStatus(state.authData.menuIds, state.authData.funcKeys)
    }
  })
}

const handleSelectDept = (dept: Dept) => {
  state.currentDept = dept
  console.log(state.currentDept)
  getDeptAuth()
}
const getDeptAuth = () => {
  state.authData = { menuIds: [], funcKeys: [] }
  deptApi.findMenus(state.currentDept.deptId).then(resp => {
    if (resp.success) {
      //都是末级菜单和权限
      state.authData = resp.data

      //递归将菜单及权限的checked更新, indeterminate
      refMenuTree.value.updateStatus(state.authData.menuIds, state.authData.funcKeys)
    }
  })
}

const handleSelectPosition = (position: Position) => {
  state.currentPosition = position
  console.log(state.currentPosition)
  getPositionAuth()
}
const getPositionAuth = () => {
  state.authData = { menuIds: [], funcKeys: [] }
  positionApi.findMenus(state.currentPosition.positionId).then(resp => {
    if (resp.success) {
      //都是末级菜单和权限
      state.authData = resp.data
      //递归将菜单及权限的checked更新, indeterminate
      refMenuTree.value.updateStatus(state.authData.menuIds, state.authData.funcKeys)
    }
  })
}

const handleAuth = (menus: any) => {
  console.log(menus)
  if (state.authType == AUTH_TYPE_ROLE) {
    roleApi
      .authMenus(
        state.currentRole.roleId,
        menus.trueNodeIds,
        menus.trueFuncKeys,
        menus.falseNodeIds,
        menus.falseFuncKeys
      )
      .then(resp => {
        if (resp.success) {
          ElMessage.success(`角色 [ ${state.currentRole.roleName} ] 的权限已更新`)
        } else {
          ElMessage.error(resp.message)
        }
      })
  }
  if (state.authType == AUTH_TYPE_DEPT) {
    deptApi
      .authMenus(
        state.currentDept.deptId,
        menus.trueNodeIds,
        menus.trueFuncKeys,
        menus.falseNodeIds,
        menus.falseFuncKeys
      )
      .then(resp => {
        if (resp.success) {
          ElMessage.success(`部门 [ ${state.currentDept.deptName} ] 的权限已更新`)
        } else {
          ElMessage.error(resp.message)
        }
      })
  }
  if (state.authType == AUTH_TYPE_POSITION) {
    positionApi
      .authMenus(
        state.currentPosition.positionId,
        menus.trueNodeIds,
        menus.trueFuncKeys,
        menus.falseNodeIds,
        menus.falseFuncKeys
      )
      .then(resp => {
        if (resp.success) {
          ElMessage.success(`职位 [ ${state.currentPosition.positionName} ] 的权限已更新`)
        } else {
          ElMessage.error(resp.message)
        }
      })
  }
}
</script>

<style lang="scss" scoped>
:deep(.splitpanes__pane) {
  background-color: #fff !important;
}
.auth-type {
  padding-left: 12px;
  background-color: #f5f7fa;
  border-bottom: 0.5px solid $--color-border-2level;
}
.role-title {
  height: 40px;
  width: 100%;
  padding-left: 10px;
  margin: 0;
  box-sizing: border-box;
  line-height: 40px;
  border-bottom: 0.5px solid $--color-border-2level;
  position: relative;
  background-color: #f5f7fa;
  color: $--color-primary;
  overflow: hidden;
  opacity: 1;
  display: flex;
  align-items: center;
  transition: opacity 0.2s;

  .empty {
    color: $--color-text-placeholder;
  }
}
</style>
